<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="id ? '编辑部门' : '添加部门'"
    width="500"
    :before-close="closeDialog"
  >
    <el-tree
      ref="treeRef"
      :data="viewData"
      check-strictly
      show-checkbox
      default-expand-all
      node-key="view_authority_id"
      highlight-current
      :props="defaultProps"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="doSubmit">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { GET_PORT_VIEW, ADD_PORT_VIEW } from '@/api/port'
import { GET_VIEW_LIST } from '@/api/view'
import getTreeData from '@/utils/arrayToTree'
const emits = defineEmits(['close'])
const { id } = defineProps(['id'])
const viewData = ref()
const defaultProps = {
  children: 'children',
  label: 'view_authority_text'
}
const treeRef = ref()
const getViewData = async () => {
  const res = await GET_VIEW_LIST()
  viewData.value = getTreeData(
    res.data,
    'view_authority_id',
    'view_authority_pid',
    'children',
    null
  )
}
getViewData()
const getDetail = () => {
  GET_PORT_VIEW(id).then((res) => {
    console.log(res)
    const checkedIds = res.data.map((item: { view_authority_id: string }) => item.view_authority_id)
    treeRef.value.setCheckedKeys(checkedIds, true)
    // const portInfo = res.data[0]
    // const info = {
    //   charge: portInfo.charge,
    //   num: portInfo.num,
    //   job: portInfo.job,
    //   name: portInfo.name,
    //   tel: portInfo.tel
    // }
    // compData.dataForm = info
  })
}
if (id) {
  getDetail()
}
const dialogFormVisible = ref(true)
const closeDialog = () => {
  emits('close')
}

//提交
const doSubmit = () => {
  console.log('doSubmit')
  const checkedIds = treeRef.value
    .getCheckedKeys()
    // .concat(treeRef.value.getHalfCheckedKeys())
    .join(',')
  const params: { id: string; view_authority_ids: string } = {
    id,
    view_authority_ids: checkedIds
  }
  ADD_PORT_VIEW(params).then((res) => {
    console.log(res)
    emits('close', true)
  })
}
</script>

<style></style>
